import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/data/models/catalog.dart';
import 'package:flutter_provider_demo/ui/catalog/catalog_viewmodel.dart';
import 'package:flutter_provider_demo/ui/profile/profile_viewmodel.dart';
import 'package:flutter_provider_demo/ui/profile/profile_widget.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class CatalogScreen extends StatefulWidget {
  const CatalogScreen({super.key, required this.viewModel});
  final CatalogViewmodel viewModel;

  @override
  State<CatalogScreen> createState() => _CatalogScreenState();
}

class _CatalogScreenState extends State<CatalogScreen> {
  // 滚动控制器
  final ScrollController _scrollController = ScrollController();
  // 下拉刷新key
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();
    widget.viewModel.loadCatalog.addListener(_onCatalogResult);
    _scrollController.addListener(_scrollListener);
    // 页面加载完成后，自动触发刷新
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshIndicatorKey.currentState?.show();
    });
  }

  @override
  void didUpdateWidget(covariant CatalogScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    oldWidget.viewModel.loadCatalog.removeListener(_onCatalogResult);
    widget.viewModel.loadCatalog.addListener(_onCatalogResult);
  }

  @override
  void dispose() {
    widget.viewModel.loadCatalog.removeListener(_onCatalogResult);
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: RefreshIndicator(
        key: _refreshIndicatorKey,
        onRefresh: () async => await widget.viewModel.loadCatalog.execute(),
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            _buildAppBar(context),
            const SliverToBoxAdapter(child: SizedBox(height: 12)),
            // 自定义顶部安全区域，由于CustomScrollView中使用SafeArea效果不理想
            // SliverPersistentHeader(delegate: MyDynamicHeader(), pinned: true,),
            _buildCatalogList(),
          ],
        ),
      ),
      drawer: ProfileDrawer(
        viewModel: ProfileViewModel(
          authRepository: context.read(),
          settingsRepository: context.read(),
        ),
      ),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    return SliverAppBar(
      title: Text(
        AppLocalizations.of(context)!.catalog,
        style: Theme.of(context).textTheme.displayLarge?.copyWith(
              color: Theme.of(context).colorScheme.onSecondary,
            ),
      ),
      floating: true,
      backgroundColor: Theme.of(context).colorScheme.secondary,
      leading: IconButton(
        color: Theme.of(context).colorScheme.onSecondary,
        icon: Icon(Icons.menu),
        onPressed: () => {
          _scaffoldKey.currentState!.openDrawer(),
        },
      ),
      actions: [
        IconButton(
          icon: Icon(Icons.shopping_cart),
          color: Theme.of(context).colorScheme.onSecondary,
          onPressed: () => context.push('/cart'),
        ),
      ],
    );
  }

  Widget _buildCatalogList() {
    return ValueListenableBuilder(
      valueListenable: widget.viewModel.catalog,
      builder: (context, catalogList, child) {
        return SliverList(
          delegate: SliverChildBuilderDelegate(
            childCount: catalogList.length + 1,
            (context, index) {
              if (index == catalogList.length) {
                return child;
              } else {
                return _CataloggItem(catalogList[index]);
              }
            },
          ),
        );
      },
      child: _buildProgressIndicator(),
    );
  }

  Widget _buildProgressIndicator() {
    return ListenableBuilder(
      listenable: widget.viewModel.loadMoreCatalog,
      builder: (constext, _) {
        if (widget.viewModel.loadMoreCatalog.running) {
          return const Padding(
            padding: EdgeInsets.all(8.0),
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        } else {
          return const SizedBox();
        }
      },
    );
  }

  void _scrollListener() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      widget.viewModel.loadMoreCatalog.execute();
    }
  }

  void _onCatalogResult() {
    if (widget.viewModel.loadCatalog.error) {
      var r = widget.viewModel.loadCatalog.result as Error;
      widget.viewModel.loadCatalog.clearResult();
      ScaffoldMessenger.of(context)
        ..clearSnackBars()
        ..showSnackBar(SnackBar(
          content: Text(r.errorMessage()),
          backgroundColor: Colors.red,
        ));
    }
  }
}

class _CataloggItem extends StatelessWidget {
  const _CataloggItem(this.catalog);
  final CatalogModel catalog;

  @override
  Widget build(BuildContext context) {
    final viewModel = context.read<CatalogViewmodel>();
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        children: [
          Container(
            width: 30,
            height: 30,
            color: catalog.color,
          ),
          const SizedBox(width: 8),
          Expanded(child: Text(catalog.name)),
          ValueListenableBuilder(
            valueListenable: viewModel.cartCatalogIds,
            builder: (context, cartCatalogIds, child) {
              final isInCart = cartCatalogIds.contains(catalog.id);
              return TextButton(
                  onPressed: () async {
                    if (isInCart) {
                      await viewModel.removeFromCart.execute(catalog.id);
                    } else {
                      await viewModel.addToCart.execute(
                        CatalogModel(
                          id: catalog.id,
                          name: catalog.name,
                          price: catalog.price,
                          color: catalog.color,
                        ),
                      );
                    }
                  },
                  style: TextButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                  ),
                  child: isInCart
                      ? Icon(Icons.check, color: Theme.of(context).colorScheme.primary)
                      : Text(AppLocalizations.of(context)!.add, style: TextStyle(color: Theme.of(context).colorScheme.primary)));
            },
          ),
        ],
      ),
    );
  }
}

// 顶部安全区域
class MyDynamicHeader extends SliverPersistentHeaderDelegate {
  int index = 0;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final double percentage = (constraints.maxHeight - minExtent) / (maxExtent - minExtent);

        if (++index > Colors.primaries.length - 1) index = 0;

        return Container(
          decoration: BoxDecoration(
            boxShadow: [BoxShadow(blurRadius: 4.0, color: Colors.black45)],
            color: Colors.red,
          ),
          height: constraints.maxHeight,
          child: SafeArea(
            child: Center(
              child: CircularProgressIndicator(
                value: percentage,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => true;

  @override
  double get maxExtent => 200.0;

  @override
  double get minExtent => 80.0;
}
